import React, { useEffect, useState, useCallback } from 'react';
import {
  Button,
  Table,
  TableColumnProps,
  Modal,
  Spin,
  Space,
  Message,
  Descriptions,
  Drawer,
} from '@arco-design/web-react';
import EditableRow from '@/pages/telepathy/educationTelepathy/sendOrRecycle/editableRow';
import EditableCell from '@/pages/telepathy/educationTelepathy/sendOrRecycle/editableCell';
import { SendOrRecycleType } from '@/pages/telepathy/educationTelepathy/enum';
import { IconEdit } from '@arco-design/web-react/icon';
import {
  getTelepathyLimitUsageInfo,
  getTelepathyLimitPage,
  getTelepathyLimitRecyclePage,
  issuedTelepathyLimit,
  recycleTelepathyLimit,
} from '@/api/wallet';
import useFetchData from '@/hooks/getList';

enum OperateNumType {
  single,
  batch,
}
enum OperateType {
  save,
  submit,
}

interface Props {
  visible: boolean;
  type: SendOrRecycleType; // 0下发灵感值，1回收灵感值
  handleChangeVisible: (visible: boolean) => void;
}
function SendOrRecycle(props: Props) {
  const { visible, type, handleChangeVisible } = props;
  const changeVisible = () => {
    handleChangeVisible(false);
  };

  let reqApi;
  if (type === SendOrRecycleType.SendInspiration) {
    reqApi = getTelepathyLimitPage;
  } else if (type === SendOrRecycleType.RecycleInspiration) {
    reqApi = getTelepathyLimitRecyclePage;
  }

  const { data, pagination, loading, getData, setData } = useFetchData(
    reqApi,
    {}
  );

  const [title, setTitle] = useState('');
  const [currQuotaTitle, setCurrQuotaTitle] = useState('');
  const [currQuotaDataIndex, setCurrDataIndex] = useState('');
  const [operateNumTitle, setOperateNumTitle] = useState('');
  const [operateTitle, setOperateTitle] = useState('');
  const [useData, setUseData] = useState([]);

  const genTitle = () => {
    switch (type) {
      case SendOrRecycleType.SendInspiration:
        setTitle('下发算力值');
        setOperateNumTitle('下发算力值');
        setCurrQuotaTitle('当前算力值');
        setCurrDataIndex('CurrentTelepathyLimit');
        setOperateTitle('下发');
        break;
      case SendOrRecycleType.RecycleInspiration:
        setTitle('回收算力值');
        setOperateNumTitle('回收算力值');
        setCurrQuotaTitle('当前算力值');
        setCurrDataIndex('CurrentTelepathyLimit');
        setOperateTitle('回收');
        break;
    }
  };

  const onOk = (pagination) => {
    const { current, pageSize } = pagination;
    const obj = {
      PageIndex: current,
      PageSize: pageSize,
    };
    getData(obj);
  };

  const [operateItems, setOperateItems] = useState([]);

  const onChangeTable = useCallback(
    (pagination) => {
      if (operateItems.length > 0) {
        Modal.confirm({
          title: '提示',
          content: `当前页未保存/${operateTitle},是否离开`,
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            onOk(pagination);
            setOperateItems([]);
          },
        });
        return;
      }
      onOk(pagination);
    },
    [operateItems, type]
  );

  const getUseData = async () => {
    if (type === SendOrRecycleType.SendInspiration) {
      const res: any = await getTelepathyLimitUsageInfo({});
      if (res.StatusCode === 200) {
        const data = [
          {
            label: '已下发算力值',
            value: res.Result.HadIssuedTelepathyLimit,
          },
          {
            label: '剩余可下发算力值',
            value: res.Result.AvailableTelepathyLimit,
          },
        ];
        setUseData(data);
      }
    }
  };

  useEffect(() => {
    if (visible) {
      setUseData([]);
      genTitle();
      getData({
        PageIndex: 1,
        PageSize: 9999,
      });
      getUseData();
    }
  }, [visible]);

  const columns: TableColumnProps[] = [
    {
      title: '序号',
      align: 'center',
      width: 80,
      render: (col, record: any, index: number) => index + 1,
    },
    {
      title: '账号',
      align: 'center',
      dataIndex: 'UserAccount',
      width: 150,
    },
    {
      title: '用户名',
      align: 'center',
      dataIndex: 'UserName',
      width: 200,
    },
    {
      title: currQuotaTitle,
      align: 'center',
      dataIndex: currQuotaDataIndex,
    },
    {
      title: operateNumTitle,
      align: 'center',
      dataIndex: 'OperateLimit',
      editable: true,
      render: (col, record, index) => (
        <span>
          {record.OperateLimit}
          <IconEdit />
        </span>
      ),
      validator: (value, callback, rowData) => {
        if (value === '') {
          return callback('请输入');
        }
        const num = Number(value);
        if (isNaN(value) || Math.floor(num) !== num || num < 0) {
          return callback('请输入正整数');
        }

        if (
          type === SendOrRecycleType.RecycleInspiration &&
          num > rowData.CurrentTelepathyLimit
        ) {
          return callback(`最多可回收${rowData.CurrentTelepathyLimit}额度`);
        }

        return callback();
      },
    },
    {
      title: '操作',
      dataIndex: 'op',
      align: 'center',
      fixed: 'right',
      render: (_, record) => (
        <div>
          <Button
            type="text"
            onClick={() => {
              handleOperate(OperateNumType.single, OperateType.submit, record);
            }}
          >
            {operateTitle}
          </Button>
        </div>
      ),
    },
  ];

  function handleSave(row) {
    const newData = [...data];
    const index = newData.findIndex((item) => row.CTLUserId === item.CTLUserId);
    newData.splice(index, 1, { ...newData[index], ...row });
    setData(newData);

    const newOperateItems = [...operateItems];
    const addIndex = newOperateItems.findIndex(
      (item) => row.CTLUserId === item.CTLUserId
    );
    if (addIndex !== -1) {
      newOperateItems[addIndex].OperateLimit = row.OperateLimit;

      const fliterItems = newOperateItems.filter(
        (item) => Number(item.OperateLimit) !== 0
      );
      setOperateItems(fliterItems);
    } else if (Number(row.OperateLimit) !== 0) {
      setOperateItems([...operateItems, row]);
    }
  }

  const handleOperate = (
    operateNumType: OperateNumType,
    operateType: OperateType,
    item?: any
  ) => {
    let currOperateItem = !!item ? item : {};

    if (item && item.OperateLimit == 0) {
      Message.error('操作项的额度不能为 0');
      return;
    }

    const newData = data.filter((item) => item.OperateLimit !== 0);
    setOperateItems(newData);
    if (!item && newData.length === 0) {
      Message.error('请编辑需要操作的数据');
      return;
    }

    updateSubmit(operateType, operateNumType, currOperateItem, newData);
  };

  const updateSubmit = async (
    operateType: OperateType,
    operateNumType: OperateNumType,
    currOperateItem: any,
    operateItems: any
  ) => {
    const isSubmit = operateType === OperateType.submit;
    let res;
    if (type === SendOrRecycleType.SendInspiration) {
      let TelepathyIssuedLimitList;
      if (operateNumType === OperateNumType.single) {
        TelepathyIssuedLimitList = [
          {
            CTLUserId: currOperateItem.CTLUserId, //C端用户id
            TelepathyIssuedLimit: Number(currOperateItem.OperateLimit), //额度
          },
        ];
      } else {
        TelepathyIssuedLimitList = operateItems.map((item) => ({
          CTLUserId: item.CTLUserId, //C端用户id
          TelepathyIssuedLimit: Number(item.OperateLimit), //额度
        }));
      }
      const reqData = {
        TelepathyLimitIssuedParams: {
          PayPassword: '', //支付密码
          ConfirmIssued: isSubmit, // 是否下发
          TelepathyIssuedLimitList,
        },
      };
      res = await issuedTelepathyLimit(reqData);
    } else if (type === SendOrRecycleType.RecycleInspiration) {
      let TelepathyRecycleLimitList;
      if (operateNumType === OperateNumType.single) {
        TelepathyRecycleLimitList = [
          {
            CTLUserId: currOperateItem.CTLUserId, //C端用户id
            TelepathyRecycleLimit: Number(currOperateItem.OperateLimit), //额度
          },
        ];
      } else {
        TelepathyRecycleLimitList = operateItems.map((item) => ({
          CTLUserId: item.CTLUserId, //C端用户id
          TelepathyRecycleLimit: Number(item.OperateLimit), //额度
        }));
      }
      const reqData = {
        TelepathyLimitRecyleParams: {
          PayPassword: '', //支付密码
          ConfirmRecycle: isSubmit, // 是否下发
          TelepathyRecycleLimitList,
        },
      };
      res = await recycleTelepathyLimit(reqData);
    }

    if (res.StatusCode === 200) {
      setOperateItems([]);
      Message.success(res.Message);
      changeVisible();
    } else {
      Message.error(res.Message);
      getData({
        PageIndex: 1,
        PageSize: 9999,
      });
    }
  };

  return (
    <>
      <Drawer
        title={title}
        visible={visible}
        autoFocus={false}
        focusLock={false}
        maskClosable={false}
        onCancel={changeVisible}
        footer={
          <Space size="small">
            <Button
              type="secondary"
              onClick={() =>
                handleOperate(OperateNumType.batch, OperateType.save)
              }
            >
              保存
            </Button>
            <Button
              type="primary"
              onClick={() =>
                handleOperate(OperateNumType.batch, OperateType.submit)
              }
            >
              {operateTitle}
            </Button>
          </Space>
        }
        style={{ width: '800px' }}
      >
        <Spin tip="加载中..." loading={loading} style={{ width: '100%' }}>
          <div
            style={{
              height: 266,
              visibility: !loading ? 'visible' : 'hidden',
            }}
          >
            {useData.length > 0 && (
              <Descriptions
                colon=" :"
                layout="inline-horizontal"
                title="使用情况"
                data={useData}
                style={{ marginBottom: '20px' }}
              />
            )}

            <Table
              border
              borderCell
              data={data}
              onChange={onChangeTable}
              rowKey="CTLUserId"
              pagination={false}
              scroll={{
                y: 650,
              }}
              components={{
                body: {
                  row: EditableRow,
                  cell: EditableCell,
                },
              }}
              columns={columns.map((column) =>
                column.editable
                  ? {
                      ...column,
                      onCell: () => ({
                        onHandleSave: handleSave,
                      }),
                    }
                  : column
              )}
              className="table-demo-editable-cell"
            />
          </div>
        </Spin>
      </Drawer>
    </>
  );
}

export default SendOrRecycle;
